﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WiimoteLib;
using System.Windows;
using System.Windows.Input;

namespace Controls.WiiMote
{
    public class WiiMoteManager
    {
        #region Properties

        public WiimoteCollection WiiMotes { get; set; }


        //private Dictionary<Guid, WiimoteInfo> mWiimoteMap = new Dictionary<Guid, WiimoteInfo>();
        #endregion

        public void Init()
        {
            // find all wiimotes connected to the system
            WiiMotes = new WiimoteCollection();
            int index = 1;

            try
            {
                WiiMotes.FindAllWiimotes();
            }
            catch (WiimoteNotFoundException ex)
            {
                MessageBox.Show(ex.Message, "Wiimote not found error");
            }
            catch (WiimoteException ex)
            {
                MessageBox.Show(ex.Message, "Wiimote error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unknown error");
            }

            foreach (Wiimote wm in WiiMotes)
            {
                // setup the map from this wiimote's ID to that control
                //WiimoteInfo wi = new WiimoteInfo(wm);
                //mWiimoteMap[wm.ID] = wi;

                // connect it and set it up as always
                wm.WiimoteChanged += wm_WiimoteChanged;
                wm.WiimoteExtensionChanged += wm_WiimoteExtensionChanged;

                wm.Connect();
                if (wm.WiimoteState.ExtensionType != ExtensionType.BalanceBoard)
                    wm.SetReportType(InputReport.IRExtensionAccel, IRSensitivity.Maximum, true);

                wm.SetLEDs(index++);
            }

        }

        void wm_WiimoteChanged(object sender, WiimoteChangedEventArgs e)
        {
            //WiimoteInfo wi = mWiimoteMap[((Wiimote)sender).ID];
            //wi.UpdateState(e);
            if (e.WiimoteState.ButtonState.Up)
            {
                this.Cursor = new Cursor(Cursor.Current.Handle);
                Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
            }
        }

        void wm_WiimoteExtensionChanged(object sender, WiimoteExtensionChangedEventArgs e)
        {
            // find the control for this Wiimote
            //WiimoteInfo wi = mWiimoteMap[((Wiimote)sender).ID];
            //wi.UpdateExtension(e);

            if (e.Inserted)
                ((Wiimote)sender).SetReportType(InputReport.IRExtensionAccel, true);
            else
                ((Wiimote)sender).SetReportType(InputReport.IRAccel, true);
        }


    }
}
